angular.module("module.memberList",[])
    .config(['$stateProvider',function ($stateProvider) {
        $stateProvider
            .state('home.memberList',{
                url:"/memberList",
                templateUrl:"memberList/memberList.html",
                controller:'MemberListController',
                controllerAs:'vm'
            })
    }])
    .controller('MemberListController',[function () {
        var vm=this;
        var para = {};
        (function table(){
            var jilu = {}, pi = 1, totalPage = 0;
            $('.container-fluid').html(template('list_tmpl', data));
            $('.pagination a').on('click', function(){
                var pi = $(this).attr('href'), query = location.search || '?', para = {};
                if (!pi) return false;
                query = query.replace(/^\?/i, '');
                if (query) {
                    $.each(query.split('&'), function(i, v){
                        var p = v.split('=');
                        if (p[0] != 'pi')para[p[0]] = p[1];
                    });
                }
                para['pi'] = pi;
                data.para=para;
                search();
                return false;
            });
            $('.reload').on('click', function(){
                window.location.reload();
            });
            $('.search').off().on('click', function(){
                var para = {};
                para.levelId = $('#searchfrom :input[name=levelId]').val() || '';
                para.memberName = $('#searchfrom :input[name=memberName]').val() || '';
                data.para=para;
                search();
            });
            $('.hisearch').off().on('click', function(){
                winAlert({
                    title:'高级查询', body:template('search_tmpl', data), btn:'查询', cancel:'取消', fun:function(){
                        var para = data.para || {};
                        para.levelId = $('.panel-table-from :input[name=levelId]').val() || '';
                        var arr = ['pay', 'score', 'ctime', 'payTime'];
                        for(i in arr){
                            if ($('.panel-table-from :input[name=start'+arr[i]+']').val())
                                para[arr[i]] = $('.panel-table-from :input[name=start'+arr[i]+']').val()+','+($('.panel-table-from :input[name=end'+arr[i]+']').val() || '')
                        }
                        console.log(para);
                        data.para=para;
                        search();
                        return true;
                    }
                });
                $('.ctime').daterangepicker({format: 'YYYY-MM-DD', parentEl:$('.ctimebox')}, function(start, end, label) {
                    var startTime = start.format('YYYY-MM-DD');
                    var endTime = end.format('YYYY-MM-DD');
                    $('.timebox :input[name=startctime]').val(startTime);
                    $('.timebox :input[name=endctime]').val(endTime);
                });
                $('.payTime').daterangepicker({format: 'YYYY-MM-DD', parentEl:$('.paytimebox')}, function(start, end, label) {
                    var startTime = start.format('YYYY-MM-DD');
                    var endTime = end.format('YYYY-MM-DD');
                    $('.timebox :input[name=startpayTime]').val(startTime);
                    $('.timebox :input[name=endpayTime]').val(endTime);
                });
            });

            function search(){ // 搜索 刷新直接调用
                var query = '?';
                data.para = data.para || {};
                $.each(data.para, function(i, v){
                    if (v)query += i+'='+encodeURI(v)+'&';
                });
                console.log(query);//return true;
                window.location.search = query;
            }
            // 查询交易记录
            $('.jiaoyi').on('click', function(){
                var i = $(this).attr('data-i');
                var vo = data.memberPage.list[i];
                $.getJSON('/uc/ajaxTradeList', {openid:vo.openid}, function(res){
                    if (!res.succeed) { alert(res.message); return false; }
                    jilu = res.data.tradePage;
                    jilu.money = vo.totalMoney;
                    jilu.giftMoney = vo.giftMoney;
                    totalPage = jilu.totalPage;
                    winAlert({
                        title:vo.memberName+'的交易记录',
                        body :template('jiaoyi_tmpl', jilu),
                        cancel:'取消'
                    });
                    var s=Date.now();
                    $('.jilu').off().scroll(function(){
                        $('#loading').show();
                        if (Date.now()-s>300 && $('.jilu .table').height() - $(this).scrollTop() - $(this).height()>50) return false;
                        if (totalPage<=pi) {
                            $('#loading').html('没有了...');
                            return false;
                        } else {
                            $('#loading').show().html('加载中...');
                        }
                        s=Date.now();
                        setTimeout(function(){
                            $.getJSON('/uc/ajaxTradeList',{openid:vo.openid, pi:pi++}, function(rs){
                                if (!rs.succeed){ toast(rs.message); return false;}
                                $('.jilu .table tbody').append(template('jilulist_tmpl', rs.data.tradePage));
                            });
                        }, 100);
                    });
                });
            });
            // 后台充值
            $('.chongzhi').off().on('click', function(){
                var i = $(this).attr('data-i');
                var vo = data.memberPage.list[i];
                winAlert({title:'请验证充值密码',body:template('checkPassword'),cancel:'取消',fun:function(){
                    var password=$(".panel input").val();
                    console.log("password",password);
                    if (password == rechargePassword){
                        checked=true;
                        $(".panel .close").trigger("click");
                        winAlert({
                            title:'后台充值', body:template('chongzhi_tmpl', data), btn:'确认充值', cancel:'取消', fun:function(){
                                var amount = $('.form-inline :input[name=amount]').val()*100;
                                var gift = $('.form-inline :input[name=gift]').val()*100;
                                if(!amount){
                                    alert("请输入充值金额");
                                    return false;
                                }
                                else if(amount==0){
                                    alert("充值金额不能为0");
                                    return false;
                                }
                                //
                                $.getJSON('/store/ajaxMemberRecharge', {openid:vo.openid, amount:amount, gift:gift}, function(res){
                                    if (res.succeed) {
                                        var memberPage = data.memberPage.list[i];
                                        var totalMoney = parseFloat(memberPage.totalMoney)+parseFloat((amount+gift)/100);
                                        var giftMoney = parseFloat(memberPage.giftMoney)+gift/100;
                                        $(".member"+i).html("￥"+totalMoney.toFixed(2)+"（含赠送金额"+giftMoney.toFixed(2)+"元）");
                                        return true;
                                    }else{
                                        alert(res.message);
                                        return false;
                                    };
                                });
                                return true;
                            }
                        });
                        $('.form-inline :input[name=amount]').keyup(function(){
                            amount(this);
                        });
                        $('.form-inline :input[name=gift]').keyup(function(){
                            amount(this);
                        });
                        $('.form-inline :input[name=amount]').blur(function(){
                            overFormat(this);
                        });
                        $('.form-inline :input[name=gift]').blur(function(){
                            overFormat(this);
                        });
                    }else {
                        return toast('密码不正确，请重新输入')
                    }
                }});
            });
            //限制输入框只能输入金额
            /**
             * 实时动态强制更改用户录入
             * arg1 inputObject
             **/
            function amount(th){
                var regStrs = [
                    ['^0(\\d+)$', '$1'], //禁止录入整数部分两位以上，但首位为0
                    ['[^\\d\\.]+$', ''], //禁止录入任何非数字和点
                    ['\\.(\\d?)\\.+', '.$1'], //禁止录入两个以上的点
                    ['^(\\d+\\.\\d{2}).+', '$1'] //禁止录入小数点后两位以上
                ];
                for(i=0; i<regStrs.length; i++){
                    var reg = new RegExp(regStrs[i][0]);
                    th.value = th.value.replace(reg, regStrs[i][1]);
                }
                if(th.value.substring(0,2)=='00'){
                    th.value = '0';
                }
            }

            /**
             * 录入完成后，输入模式失去焦点后对录入进行判断并强制更改，并对小数点进行0补全
             * arg1 inputObject
             * 这个函数写得很傻，是我很早以前写的了，没有进行优化，但功能十分齐全，你尝试着使用
             * 其实有一种可以更快速的JavaScript内置函数可以提取杂乱数据中的数字：
             * parseFloat('10');
             **/
            function overFormat(th){
                var v = th.value;
                if(v === ''){
                    v = '0.00';
                }else if(v === '0'){
                    v = '0.00';
                }else if(v === '0.'){
                    v = '0.00';
                }else if(/^0+\d+\.?\d*.*$/.test(v)){
                    v = v.replace(/^0+(\d+\.?\d*).*$/, '$1');
                    v = inp.getRightPriceFormat(v).val;
                }else if(/^0\.\d$/.test(v)){
                    v = v + '0';
                }else if(!/^\d+\.\d{2}$/.test(v)){
                    if(/^\d+\.\d{2}.+/.test(v)){
                        v = v.replace(/^(\d+\.\d{2}).*$/, '$1');
                    }else if(/^\d+$/.test(v)){
                        v = v + '.00';
                    }else if(/^\d+\.$/.test(v)){
                        v = v + '00';
                    }else if(/^\d+\.\d$/.test(v)){
                        v = v + '0';
                    }else if(/^[^\d]+\d+\.?\d*$/.test(v)){
                        v = v.replace(/^[^\d]+(\d+\.?\d*)$/, '$1');
                    }else if(/\d+/.test(v)){
                        v = v.replace(/^[^\d]*(\d+\.?\d*).*$/, '$1');
                        ty = false;
                    }else if(/^0+\d+\.?\d*$/.test(v)){
                        v = v.replace(/^0+(\d+\.?\d*)$/, '$1');
                        ty = false;
                    }else{
                        v = '0.00';
                    }
                }
                th.value = v;
            }
        })();
    }]);